// window.billId = 123
layui.use(['form', 'element', 'miniPage', 'utils', 'upload', 'laytpl', 'xmSelect', 'laydate'], function () {
    var $ = layui.jquery,
        layer = layui.layer,
        form = layui.form,
        element = layui.element,
        miniPage = layui.miniPage,
        utils = layui.utils,
        laytpl = layui.laytpl,
        upload = layui.upload,
        xmSelect = layui.xmSelect,
        laydate = layui.laydate;

    // 当前弹出层，防止ID被覆盖
    var parentIndex = layer.index;

    /**
     *  定义模板
     */
    var tplTalent = $('#tplTalent').html(); //候选人
    var tplCharge = $('#tplCharge').html(); // 收费信息
    var tplAchievement = $('#achievement').html(); // 业绩分配
    var tplPaymentInfo = $('#tplPaymentInfo').html(); // 付款信息

    /**
     *  定义组件
     */
    Vue.component('inputNumber', {
        template: '<input type="text" :value="displayValue"' +
            ' :placeholder="placeholder"' +
            ' :lay-verify="layVerify"' +
            ' autocomplete="off"' +
            ' class="layui-input" min="0" max="100"' +
            ' @blur="handleBlur" @focus="handleFocus" @input="handleInput" @change="handleInputChange" />',
        props: {
            max: {
                type: Number,
                default: Infinity
            },
            min: {
                type: Number,
                default: -Infinity
            },
            value: {},
            disabled: Boolean,
            placeholder: String,
            layVerify: String,
            precision: {
                type: Number,
                validator: function(val) {
                    return val >= 0 && val === parseInt(val, 10);
                }
            }
        },
        data: function () {
            return {
                currentValue: 0,
                userInput: null
            }
        },
        computed: {
            displayValue() {
                if (this.userInput !== null) {
                    return this.userInput;
                }

                var currentValue = this.currentValue;

                if (typeof currentValue === 'number') {
                    if (this.precision !== undefined) {
                        currentValue = currentValue.toFixed(this.precision);
                    }
                }
                return currentValue;
            }
        },
        watch: {
            value: {
                immediate: true,
                handler: function(value) {
                    var newVal = value === undefined ? value : Number(value);
                    if (newVal !== undefined) {
                        if (_.isNaN(newVal)) {
                            return;
                        }

                        if (this.precision !== undefined) {
                            newVal = this.toPrecision(newVal, this.precision);
                        }
                    }
                    if (newVal >= this.max) newVal = this.max;
                    if (newVal <= this.min) newVal = this.min;
                    this.currentValue = newVal;
                    this.userInput = null;
                    this.$emit('input', newVal);
                }
            }
        },
        methods: {
            toPrecision: function (num, precision) {
                if (precision === undefined) precision = this.precision;
                return parseFloat(Math.round(num * Math.pow(10, precision)) / Math.pow(10, precision));
            },
            handleBlur: function(event) {
                this.$emit('blur', event);
            },
            handleFocus: function (event) {
                this.$emit('focus', event);
            },
            handleInput: function(event) {
                var target = event.currentTarget || event.target
                this.userInput = target.value
            },
            setCurrentValue: function(newVal) {
                var oldVal = this.currentValue;
                if (typeof newVal === 'number' && this.precision !== undefined) {
                    newVal = this.toPrecision(newVal, this.precision);
                }
                if (newVal >= this.max) newVal = this.max;
                if (newVal <= this.min) newVal = this.min;
                if (oldVal === newVal) return;
                this.userInput = null;
                this.$emit('input', newVal);
                this.$emit('change', newVal, oldVal);
                this.currentValue = newVal;
            },
            handleInputChange: function (event) {
                var target = event.currentTarget || event.target
                var value = target.value
                var newVal = value === '' ? undefined : Number(value);
                if (!isNaN(newVal) || value === '') {
                    this.setCurrentValue(newVal);
                }
                this.userInput = null;
            }
        }
    })

    // 收费信息
    Vue.component('chargeItem', {
        template: tplCharge,
        props: {
            data: {
                type: Object,
                default: function () {
                    return {}
                }
            },
            deleteable: {
                type: Boolean,
                default: true
            },
            chargeType: {
                type: Array,
                default: function () {
                    return []
                }
            },
            supplier: {
                type: Array,
                default: function () {
                    return []
                }
            }
        },
        data: function () {
            return {
                _isMounted: false,
                form: {
                    id: '',
                    itemId: '',
                    billAmount: '',
                    payAmount: '',
                    vendor: '',
                    isNew: false
                },
                xmSelectItem: null,
                chargeTypeSelect: null,
                supplierSelect: null
            }
        },
        watch: {
            data: {
                handler: function (value) {
                    if (value) {
                        utils.copyObject(this.form, value)
                    }
                    this.initChargeType()
                    this.initSupplier()
                },
                immediate: true
            },
            chargeType: {
                handler: function (value) {
                    this.initChargeType()
                }
            },
            supplier: {
                handler: function (value) {
                    this.initSupplier()
                }
            },
            // 'form.payAmount': {
            //     handler: function (value) {
            //         if (value) {
            //             this.supplierSelect.update({
            //                 layVerify: 'required'
            //             })
            //         }
            //     }
            // }
        },
        mounted: function() {
            this._isMounted = true
            this.initChargeType()
            this.initSupplier()
        },
        methods: {
            getData: function () {
                var obj = {};
                var newIgnoreKey = ['id', 'isNew'];
                var ignoreKey = ['isNew'];
                if (this.form.isNew) {
                    utils.copyObjectWithIgnoreKey(obj, this.form, newIgnoreKey)
                } else {
                    utils.copyObjectWithIgnoreKey(obj, this.form, ignoreKey)
                }
                return obj;
            },
            getIncomeAmount: function () {
                return this.form.billAmount
            },
            handleDeleteCharge: function () {
                this.$emit('delete', this.form.id)
            },
            initChargeType: function () {
                var that = this;
                var $chargeTypeSelect = that.$refs.chargeTypeSelect;
                if (!$chargeTypeSelect) {
                    return null
                }
                var initValue = this.form.itemId ? [this.form.itemId] : [];
                if (!this.chargeTypeSelect) {
                    this.chargeTypeSelect = xmSelect.render({
                        el: $chargeTypeSelect,
                        radio: true,
                        clickClose: true,
                        layVerify: 'required',
                        model: {
                            icon: 'hidden'
                        },
                        prop: {
                            name: 'text',
                            value: 'id',
                        },
                        name: 'itemId',
                        theme: {
                            color: '#84d0e8',
                        },
                        filterable: true,
                        data: this.chargeType,
                        initValue: initValue,
                        on: function (data) {
                            var arr = data.arr;
                            if (arr.length) {
                                that.form.itemId = arr[0].id;
                            } else {
                                that.form.itemId = '';
                            }
                        }
                    });
                } else {
                    this.chargeTypeSelect.update({
                        data: this.chargeType,
                        initValue: initValue
                    });
                }
            },
            initSupplier: function () {
                var that = this;
                var $supplierSelect = that.$refs.supplierSelect;
                if (!$supplierSelect) {
                    return null
                }
                var initValue = this.form.vendor ? [this.form.vendor] : []
                if(!this.supplierSelect) {
                    this.supplierSelect = xmSelect.render({
                        el: $supplierSelect,
                        radio: true,
                        clickClose: true,
                        model: {
                            icon: 'hidden'
                        },
                        prop: {
                            name: 'vendorName',
                            value: 'id',
                        },
                        name: 'vendor',
                        theme: {
                            color: '#84d0e8',
                        },
                        filterable: true,
                        data: this.supplier,
                        initValue: initValue,
                        on: function (data) {
                            var arr = data.arr;
                            if (arr.length) {
                                that.form.vendor = arr[0].id;
                            } else {
                                that.form.vendor = '';
                            }
                        }
                    })
                } else {
                    this.supplierSelect.update({
                        data: this.supplier,
                        initValue: initValue
                    });
                }
            },
            handleIncomeAmountChange: function () {
                this.$emit('income-change', this.form.billAmount)
            },
            handleAmountBlur: function () {
                if (this.form.payAmount) {
                    this.supplierSelect.update({
                        layVerify: 'required'
                    })
                } else {
                    this.supplierSelect.update({
                        layVerify: ''
                    })
                }
            }
        },
    });

    Vue.component('achievementItem', {
        template: tplAchievement,
        props: {
            data: {
                type: Object,
                default: function () {
                    return {}
                }
            },
            deleteable: {
                type: Boolean,
                default: true
            },
            invoiceAmount: {
                type: [Number, String],
                default: 0
            },
            distributionType: {
                type: Array,
                default: function () {
                    return []
                }
            }
        },
        data: function () {
            return {
                form: {
                    id: '',
                    distributionUserEnglishName: '',
                    participantType: '',
                    distributionProportion: '',
                    distributionAmount: '',
                    distributionType: '',
                    reasonText: '',
                    isNew: false
                }
            }
        },
        mounted: function () {
            var that = this;
            form.render();
            form.on('select(distributionType-' + that.form.id + ')' , function (data) {
                that.form.distributionType = data.value;
            });
        },
        watch: {
            data: {
                handler: function (value) {
                    if (value) {
                        utils.copyObject(this.form, value)
                    }
                    var distributionProportion = this.form.distributionProportion ? +this.form.distributionProportion : 0
                    this.form.distributionAmount = (distributionProportion * this.invoiceAmount).toFixed(2)
                },
                immediate: true
            },
            invoiceAmount: function () {
                var distributionProportion = this.form.distributionProportion ? +this.form.distributionProportion : 0
                this.form.distributionAmount = (distributionProportion * this.invoiceAmount / 100).toFixed(2)
            },
            'form.distributionProportion': function () {
                var distributionProportion = this.form.distributionProportion ? +this.form.distributionProportion : 0
                this.form.distributionAmount = (distributionProportion * this.invoiceAmount / 100).toFixed(2)
            },
            'form.distributionAmount': function () {
                var distributionAmount = this.form.distributionAmount;
                this.form.distributionProportion = ((this.form.distributionAmount / this.invoiceAmount)*100).toFixed(2)
            },
            distributionType: {
                handler: function (value) {
                    this.$nextTick(function() {
                        form.render();
                    })
                },
                immediate: true
            },
        },
        methods: {
            getData: function () {
                var obj = {};
                var newIgnoreKey = ['id', 'isNew'];
                var ignoreKey = ['isNew'];
                if (this.form.isNew) {
                    utils.copyObjectWithIgnoreKey(obj, this.form, newIgnoreKey)
                } else {
                    utils.copyObjectWithIgnoreKey(obj, this.form, ignoreKey)
                }
                return obj;
            },
            handleDeleteAchievement: function () {
                this.$emit('delete', this.form.id)
            },
        },
    });

    Vue.component('talentItem', {
        template: tplTalent,
        props: {
            data: {
                type: Object,
                default: function () {
                    return {}
                }
            },
            deleteable: {
                type: Boolean,
                default: true
            },
            addable: {
                type: Boolean,
                default: true
            },
            number: {
                type: Number,
                default: 0
            },
            chargeType: {
                type: Array,
                default: function () {
                    return []
                }
            },
            supplier: {
                type: Array,
                default: function () {
                    return []
                }
            },
            receiptType: {
                type: Array,
                default: function () {
                    return []
                }
            },
            // invoiceType: {
            //     type: Array,
            //     default: function () {
            //         return []
            //     }
            // },
            distributionType: {
                type: Array,
                default: function () {
                    return []
                }
            },
            paymentData: {
                type: Array,
                default: function () {
                    return []
                }
            }
        },
        created: function () {
        },
        data: function () {
            return {
                form: {
                    id: '',
                    talentId: '', //候选人发票信息id
                    clientId: '',
                    orderId: '',
                    talentNameCn: '', // 姓名
                    onboardDate: '', // 预计入职时间
                    guaranteeDate: '', // 保证期

                    billAmount: 0, // 金额
                    receiptType: '',
                    receiptPercent: '',
                    // invoiceBillingType: '', // invoiceType
                    invoiceComment: '', // 收费备注

                    clientBillingNumber: '', // 付款信息

                    isNew: false,
                },
                chargeList: [],
                fileList: [],

                achievementList: [], // 已选择顾问
                allAchievement: [], // 全部顾问

                payInfo: {
                    billingType: '',
                    invoiceTitle: '',
                    clientTaxCode: '',
                    registerAddress: '',
                    registerPhone: '',
                    bankAccountName: '',
                    bankAccountCode: '',

                    contact: {
                        contactName: '',
                        mobile: '',
                        email: '',
                        address: '',
                        clientName: '',
                        contactTitle: ''
                    },
                    id: '',
                    createBy: '',
                    createTime: '',
                    modifyBy: '',
                    modifyTime: '',
                    dataSourceCode: ''
                }, // 付款信息-发票信息
                paymentSelect: null
            }
        },
        computed: {
            // 可以选择的用户
            canSelectUsers: function () {
                var selectedUsersIds = [];
                this.achievementList.forEach(function (item) {
                    selectedUsersIds.push(item.userId)
                });
                var canSelectUsers = _.filter(this.allAchievement, function (obj) {
                    return selectedUsersIds.indexOf(obj.userId) === -1
                });

                return canSelectUsers;
            }
        },

        mounted: function () {
            var that = this;
            form.render();
            element.render(); // 折叠
            form.on('select(receiptType-' + that.form.id + ')', function (data) {
                that.form.receiptType = data.value;
                if (data.value == 477) {
                    that.form.receiptPercent = 100;
                } else {
                    that.form.receiptPercent = 0;
                }
            });

            // form.on('select(invoiceType)', function (data) {
            //     that.form.invoiceBillingType = data.value;
            // });

            // 上传
            var $uploadFile = that.$refs.uploadFile;
            upload.render({
                elem: $uploadFile,
                headers: {token: window.sessionStorage.getItem("token")},
                url: '/baseMailAttachment/upload',
                accept: 'file',
                data: {
                    type: ''
                },
                before: function (obj) {
                    // var _temp = '<div class="layui-progress layui-progress-big mt-10" lay-filter="progress">' +
                    //     '<div class="layui-progress-bar layui-bg-lightblue"></div>' +
                    //     '</div>';
                    // $($uploadFile).after(_temp);
                    $($uploadFile).append(' <i class="layui-icon layui-icon-loading layui-icon layui-anim layui-anim-rotate layui-anim-loop"></i>');
                },
                progress: function (n, elem) {
                    var percent = n + '%';
                    element.progress('progress', percent);
                },
                done: function (res) {
                    if (res.code === 200) {
                        // 移除进度条
                        $($uploadFile).next('.layui-progress').remove();
                        // 更新列表
                        // that.getFileList();

                        that.fileList.unshift(res.data);
                        $($uploadFile).find('.layui-icon').remove();
                    }
                },
                error: function () {
                    layer.msg('请求错误！');
                }
            });
            // 预计入职时间
            // that.onboardDate();

            // 用户
            that.getAllAchievement();
            // 客户
            console.log('length', !that.paymentData.length);
            if (!that.paymentSelect && (that.paymentData.length > 0)) {
                console.log(2222222)
                that.paymentSelect = that.initPayment()
            }
            // that.initPayment();
            //that.getPaymentData(that.form.clientBillingNumber);
        },
        watch: {
            data: {
                handler: function (value) {
                    if (value) {
                        utils.copySelfObject(this.form, value);
                        if (Array.isArray(value.jobInvoiceItems) && value.jobInvoiceItems.length) {
                            this.chargeList = value.jobInvoiceItems;
                        }
                        if (Array.isArray(value.jobInvoiceFiles) && value.jobInvoiceFiles.length) {
                            this.fileList = value.jobInvoiceFiles;
                        }
                        if (Array.isArray(value.jobInvoiceDistributions) && value.jobInvoiceDistributions.length) {
                            this.achievementList = value.jobInvoiceDistributions;
                        }
                    }
                },
                immediate: true
            },
            chargeList: {
                handler: function (value) {
                    if (value && value.length) {
                        this.chargeList = value
                    } else {
                        this.chargeList = [
                            this.createChargeItem() //创建新的item
                        ]
                    }
                },
                immediate: true
            },
            achievementList: {
                handler: function (value) {
                    if (value && value.length) {
                        this.achievementList = value
                    }
                },
                immediate: true
            },
            allAchievement: {
                handler: function (value) {
                    var that = this;
                    if (value && value.length) {
                        value.forEach(function (item) {
                            var obj = item;
                            // obj.achievementId = item.id;
                            obj.distributionUserEnglishName = item.userEnglishName;
                            // delete obj.id;
                            delete obj.userEnglishName;

                            if (!item.editable) {
                                //that.addAchievementItem(obj);
                            }
                        });
                    }
                },
                immediate: true
            },
            // invoiceType: {
            //     handler: function() {
            //         this.$nextTick(function() {
            //             form.render();
            //         })
            //     }
            // },
            receiptType: {
                handler: function() {
                    this.$nextTick(function() {
                        form.render();
                    })
                },
            },
            paymentData: {
                handler: function (value) {
                    console.log('watch')
                    if (!this.paymentSelect) {
                        this.paymentSelect = this.initPayment()
                    }
                }
            },
        },
        methods: {
            getData: function () {
                var obj = {};
                var newIgnoreKey = ['id', 'isNew'];
                var ignoreKey = ['isNew'];
                if (this.form.isNew) {
                    utils.copyObjectWithIgnoreKey(obj, this.form, newIgnoreKey)
                } else {
                    utils.copyObjectWithIgnoreKey(obj, this.form, ignoreKey)
                }

                // 收费信息
                var $chargeItem = this.$refs.chargeItem;
                var chargeInfo = [];
                $chargeItem.forEach(function(item) {
                    chargeInfo.push(item.getData())
                });
                obj.jobInvoiceItems = chargeInfo;

                // // 上传附件
                // obj.jobInvoiceFiles = this.getFileData();
                obj.jobInvoiceFiles = this.fileList;

                // 业绩分配
                var $achievementItem = this.$refs.achievementItem;
                var achievementInfo = [];
                if ($achievementItem) {
                    $achievementItem.forEach(function(item) {
                        achievementInfo.push(item.getData())
                    });
                }
                obj.jobInvoiceDistributions = achievementInfo;

                return obj;
            },
            handleAddBtnClick: function () {
                this.$emit('add', this.data)
            },
            handleDelete: function () {
                this.$emit('remove', this.data)
            },
            // onboardDate: function () {
            //     var that = this;
            //     var $onboardDate = that.$refs.onboardDate;
            //     laydate.render({
            //         elem: $onboardDate,
            //         trigger: 'click',
            //         done: function(value, date, endDate){
            //             that.form.onboardDate = value;
            //         }
            //     });
            // },

            createChargeItem: function () {
                return {
                    id: utils.generateUUID(),
                    itemId: '',
                    billAmount: '',
                    payAmount: '',
                    vendor: '',
                    isNew: true
                }
            },
            handleAddCharge: function () {
                var that = this;
                var item = this.createChargeItem();
                that.chargeList.push(item);
                that.$nextTick(function () {
                    form.render();
                })
            },
            handleDeleteCharge: function (id) {
                for (var index = 0; index < this.chargeList.length; index++) {
                    if (this.chargeList[index].id === id) {
                        this.chargeList.splice(index, 1);
                        break
                    }
                }
                var that = this
                this.$nextTick(function () {
                    that.computedTotalIncome()
                })
            },
            handleIncomeAmountChange: function () {
                this.computedTotalIncome()
            },
            computedTotalIncome: function() {
                var $chargeItems = this.$refs.chargeItem;
                var that = this;
                this.form.billAmount = 0;
                if (Array.isArray($chargeItems) && $chargeItems.length) {
                    $chargeItems.forEach(function ($el) {
                        var itemIncome = $el.getIncomeAmount()
                        that.form.billAmount += itemIncome
                    })
                }
            },

            // getFileList: function () {
            //     var that = this;
            //     utils.Ajax({
            //         url: 'api/talent_file_list.json',
            //         dataType: 'json',
            //         contentType: 'application/json',
            //         type: 'post',
            //         data: {id: that.form.id},
            //         success: function (response) {
            //             var data = response.data;
            //             that.fileList = data.fileList;
            //         }
            //     })
            // }, // 附件
            handleDeleteFile: function(id) {
                for (var index = 0; index < this.fileList.length; index++) {
                    if (this.fileList[index].id === id) {
                        this.fileList.splice(index, 1);
                        return
                    }
                }
            },
            getFileData: function () {
                var arr = [];
                $.each(this.fileList, function (index, item) {
                    arr.push(item.id)
                });
                return arr;
            },

            getAllAchievement: function () {
                var that = this;
                utils.Ajax({
                    url: 'jobOrderParticipant/getList',
                    dataType: 'json',
                    type: 'post',
                    data: JSON.stringify({orderId: that.form.orderId}),
                    success: function (response) {
                        var data = response.data;
                        if (Array.isArray(data)) {
                            that.allAchievement = data;
                        } else {
                            that.allAchievement = [];
                        }

                    }
                })
            },

            createAchievementItem: function (selectedUser) {
                // return {
                //     id: utils.generateUUID(),
                //     talentId: selectedUser.talentId,
                //     name: selectedUser.name,
                //     job: selectedUser.job,
                //     distributionProportion: selectedUser.distributionProportion,
                //     distributionAmount: selectedUser.distributionAmount,
                //     isNew: true
                // }
                var obj = {};
                obj = selectedUser;
                // obj.id = utils.generateUUID();

                return obj;
            },
            addAchievementItem: function(selectedUser) {
                var newItem = this.createAchievementItem(selectedUser);
                this.achievementList.push(newItem)
            }, // 添加用户
            handleAddAchievement: function () {
                var that = this;

                laytpl($('#tplCanSelectUser').html()).render(that.canSelectUsers, function(html){
                    layer.open({
                        title: '新增用户',
                        type: 1,
                        shade: 0.2,
                        area: ['1000px', '90%'],
                        content: html,
                        btn: ['确认', '取消'],
                        btnAlign: 'c',
                        success: function(layero, index){
                            form.render();
                            var userCb = [];
                            form.on('checkbox(userCb)', function(data){
                                if (data.elem.checked) {
                                    userCb.push(parseInt(data.value))
                                } else {
                                    var index = userCb.indexOf(data.value);
                                    userCb.splice(index, 1);
                                }
                            });

                            form.on('submit(formSub)', function(data){
                                var newSelectUser = _.filter(that.canSelectUsers, function (obj) {
                                    return userCb.indexOf(obj.userId) > -1
                                });
                                newSelectUser.forEach(function (item) {
                                    that.addAchievementItem(item);
                                });
                                layer.close(index);
                                return false;
                            });
                        },
                        yes: function (index, layero) {
                            layero.find('[lay-filter="formSub"]').click();
                        }
                    });
                });
            },
            handleDeleteAchievement: function (id) {
                for (var index = 0; index < this.achievementList.length; index++) {
                    if (this.achievementList[index].id === id) {
                        this.achievementList.splice(index, 1);
                        return
                    }
                }
            },

            initPayment: function () {
                var that = this;
                var $paymentSelect = that.$refs.paymentSelect;
                if (!$paymentSelect) {
                    return null
                }
                var xmSelectItem = xmSelect.render({
                    el: $paymentSelect,
                    radio: true,
                    clickClose: true,
                    model: {
                        icon: 'hidden'
                    },
                    prop: {
                        name: 'invoiceTitle',
                        value: 'id',
                    },
                    name: 'clientBillingNumber',
                    layVerify: 'required',
                    theme: {
                        color: '#84d0e8',
                    },
                    filterable: true,
                    data: that.paymentData,
                    initValue: [that.form.clientBillingNumber],
                    on: function (data) {
                        var arr = data.arr;
                        if (arr.length) {
                            that.form.clientBillingNumber = arr[0].id;
                            // 客户信息
                            that.getPaymentInfo(that.form.clientBillingNumber);
                        } else {
                            that.form.clientBillingNumber = '';
                        }
                    }
                });

                if (that.form.clientBillingNumber) {
                    that.getPaymentInfo(that.form.clientBillingNumber);
                }

                return xmSelectItem;
            },
            // getPaymentData: function (val) {
            //     var that = this;
            //     utils.Ajax({
            //         url: 'clnBilling/getList',
            //         dataType: 'json',
            //         type: 'post',
            //         data: JSON.stringify({clientId: that.form.clientId}),
            //         success: function (response) {
            //             var list = response.data;
            //
            //             var initValue = val === undefined ? [] : [val];
            //             if (!Array.isArray(list)) list = [];
            //
            //             that.initPayment().update({
            //                 data: list,
            //                 initValue: initValue
            //             });
            //
            //             if (val) {
            //                 that.getPaymentInfo(val);
            //             }
            //         }
            //     });
            // }, // 客户选项
            getPaymentInfo: function (id) {
                var that = this;
                utils.Ajax({
                    url: '/clnBilling/billinginfo',
                    dataType: 'json',
                    type: 'post',
                    data: JSON.stringify({id: id}),
                    success: function (response) {
                        var data = response.data;
                        utils.copySelfObject(that.payInfo, data);
                    }
                });
            }, // 客户信息
            editPaymentInfo: function () {
                if (!this.form.clientBillingNumber) return;
                var content = miniPage.getHrefContent('page/finance/public/addBillInfo.html?id=' + this.form.clientBillingNumber);
                if (content) {
                    layer.open({
                        title: '付款信息',
                        type: 1,
                        shade: 0.2,
                        area: ['100%', '90%'],
                        content: content,
                        btn: ['确认', '取消'],
                        btnAlign: 'c',
                        yes: function (index, layero) {
                            layero.find('[lay-filter="saveBtn"]').click();
                        }
                    });
                }
            }, // 编辑付款信息
            addPaymentInfo: function () {
                var that = this;
                var content = miniPage.getHrefContent('page/finance/public/addBillInfo.html');
                if (content) {
                    layer.open({
                        title: '付款信息',
                        type: 1,
                        shade: 0.2,
                        area: ['100%', '90%'],
                        content: content,
                        btn: ['确认', '取消'],
                        btnAlign: 'c',
                        yes: function (index, layero) {
                            layero.find('[lay-filter="saveBtn"]').click();
                            that.getPaymentData(that.form.clientBillingNumber);
                        }
                    });
                }
            }, // 添加付款信息
        },
    });

    var addBillContent = new Vue({
        el: '#addBillContent',
        data: function () {
            return {
                billId: null,
                form: {
                    billingType: 0,
                    batchFrom: 'project',
                    projectId: '', // 项目
                    projectName: '',
                    orderId: '', // 订单
                    positionName: '',

                    clientId: '', // 客户id

                    contractNumber: '', // 合同
                    poNumber: '',
                    expressNumber: '', // 快递单号
                    expressCompany: '', // 快递公司
                    paymentTerms: '', // Payment Terms
                    invoiceNo: '', // 税务发票号

                    invoiceBillingType: '',

                    printStatus: 0, // 打印状态
                    payStatus: 0, // 收款状态
                    submitToBilling: 0, //submit To Billing
                },
                addAfterIndex: '',
                jobInvoiceVos: [], // 候选人列表
                allTalent: [], // 符合条件的全部候选人

                chargeType: [],// 类型
                supplier: [], // 供应商

                receiptType: [], // 收款比列类别
                invoiceType: [],
                distributionType: [],

                paymentData: [],

                resultFlag: true,
                agreementSelect: null,
            }
        },
        watch: {
            invoiceType: {
                handler: function() {
                    this.$nextTick(function() {
                        form.render();
                    })
                }
            }
        },
        computed: {
            // 可以选择的候选人
            canSelectTalent: function () {
                var selectedUsersIds = [];
                this.jobInvoiceVos.forEach(function (item) {
                    selectedUsersIds.push(item.talentId)
                });
                var canSelectTalent = _.filter(this.allTalent, function (obj) {
                    return selectedUsersIds.indexOf(obj.talentId) === -1
                });
                return canSelectTalent;
            }
        },
        mounted: function () {
            if (window.billId) {
                this.billId = window.billId
                this.getInfo();
            } else {
                this.initForm();
            }
            // this.initForm();
        },
        methods: {
            getInfo: function () {
                var that = this;
                utils.Ajax({
                    url: 'jobInvoiceBatch/getList',
                    dataType: 'json',
                    contentType: 'application/json',
                    type: 'POST',
                    data: JSON.stringify({id: window.billId}),
                    success: function (response) {
                        var data = response.data;
                        if(Array.isArray(data) && data.length) {
                            that.initFormData(data[0])
                        }
                        // 重新渲染表单
                        that.initForm();
                    }
                })
            },
            initFormData: function(data) {
                utils.copyObject(this.form, data); //基础表单
                this.resultFlag = false;
                if (Array.isArray(data.jobInvoiceVos) && data.jobInvoiceVos.length) {
                    this.jobInvoiceVos = data.jobInvoiceVos
                }
                this.form.billingType = (data.batchFrom === 'order') ? 1 : 0
            },
            initForm: function () {
                var that = this;

                form.render();

                if (that.form.billingType == 0) {
                    that.$nextTick(function () {
                        that.form.batchFrom = 'project';
                        that.initProject();
                    })
                } else if (that.form.billingType == 1) {
                    that.$nextTick(function () {
                        that.form.batchFrom = 'order';
                        that.initOrder();
                    })
                }

                if (that.form.clientId) {
                    that.getPaymentData();
                }
                // that.initProject();

                that.getChargeTypeData();
                that.getSupplierData();

                that.getReceiptType(); // 收款比列类别
                that.getInvoiceType(); // 开票类型
                that.getReasonType(); // 分成原因

                that.getAgreementData(); // 合同

                that.getPaymentTerms(that.form.paymentTerms);

                // 开票类型
                form.on('radio(billingType)', function (data) {
                    that.form.billingType = data.value;

                    that.form.projectId = '';
                    that.form.orderId = '';
                    that.form.clientId = '';
                    that.form.projectName = '';
                    that.form.positionName = '';

                    that.form.batchFrom = '';

                    that.jobInvoiceVos = [];

                    if (data.value == 0) {
                        that.$nextTick(function () {
                            that.form.batchFrom = 'project';
                            that.initProject();
                        })
                    } else if (data.value == 1) {
                        that.$nextTick(function () {
                            that.form.batchFrom = 'order';
                            that.initOrder();
                        })
                    }
                });

                // Payment Terms
                // form.on('select(paymentTerms)', function (data) {
                //     that.form.paymentTerms = data.value;
                // });

                form.on('select(invoiceType)', function (data) {
                    that.form.invoiceBillingType = data.value;
                });

                // submit to billing
                form.on('checkbox(submitToBilling)', function (data) {
                    if (data.elem.checked) {
                        that.form.submitToBilling = 1;
                    }else{
                        that.form.submitToBilling = 0;
                    }
                });

                // 检测
                form.on('submit(billSub)', function (data) {
                    that.handleSubmitBtnClick();
                });
            },

            initProject: function () {
                var that = this;
                var $projectSelect = that.$refs.projectSelect;
                if (!$projectSelect) {
                    return null
                }
                // var initValue = that.form.projectId === undefined ? [] : [that.form.projectId];
                var xmSelectItem = xmSelect.render({
                    el: $projectSelect,
                    radio: true,
                    clickClose: true,
                    model: {
                        icon: 'hidden'
                    },
                    prop: {
                        name: 'projectName',
                        value: 'id',
                    },
                    name: 'projectId',
                    layVerify: 'required',
                    theme: {
                        color: '#84d0e8',
                    },
                    filterable: true,
                    paging: true,
                    pageRemote: true,
                    pageEmptyShow: false,
                    remoteMethod: function(val, cb, show, pageIndex) {
                        // if(!val){
                        //     return cb([]);
                        // }
                        var datas = {
                            pageIndex: pageIndex,
                            pageSize: 10,
                            keywords: val
                        };
                        utils.Ajax({
                            url: 'jobProject/getPageList',
                            dataType: 'json',
                            type: 'post',
                            data: JSON.stringify(datas),
                            success: function(response) {
                                var res = response.data;
                                if(_.isArray(res.records) && res.records.length) {
                                    //回调需要两个参数, 第一个: 数据数组, 第二个: 总页码
                                    cb(res.records, Math.ceil(res.total/datas.pageSize));
                                } else {
                                    cb([], 0);
                                }
                            }
                        })
                    },
                    on: function (data) {
                        var arr = data.arr;
                        if (arr.length) {
                            var projectId = arr[0].id;
                            var clientId = arr[0].clientId;
                            var projectName = arr[0].projectName;

                            if(projectId !== that.form.projectId) {
                                that.form.projectId = projectId;
                                that.form.clientId = clientId;
                                that.form.projectName = projectName;

                                that.jobInvoiceVos = []
                            }
                            that.resultFlag = true;
                            that.getAllTalent(that.form.projectId);

                            that.paymentData=[];
                            that.getPaymentData();
                        } else{
                            that.form.projectId = '';
                            that.form.clientId = '';
                            that.form.projectName = '';
                            // that.jobInvoiceVos = [];
                        }
                        that.getAgreementData(); // 合同
                    }
                });

                // xmSelectItem.setValue([
                //     {projectName: '我可以吗', id: 3069},
                // ])

                if (that.form.projectId) {
                    xmSelectItem.setValue([
                        { projectName: that.form.projectName, id: that.form.projectId},
                    ])
                }

                return xmSelectItem;
            }, // 项目

            initOrder: function () {
                var that = this;
                var $orderSelect = that.$refs.orderSelect;
                if (!$orderSelect) {
                    return null
                }
                // var initValue = that.form.projectId === undefined ? [] : [that.form.projectId];
                var xmSelectItem = xmSelect.render({
                    el: $orderSelect,
                    radio: true,
                    clickClose: true,
                    model: {
                        icon: 'hidden'
                    },
                    prop: {
                        name: 'positionName',
                        value: 'id',
                    },
                    name: 'orderId',
                    layVerify: 'required',
                    theme: {
                        color: '#84d0e8',
                    },
                    filterable: true,
                    paging: true,
                    pageRemote: true,
                    pageEmptyShow: false,
                    remoteMethod: function(val, cb, show, pageIndex) {
                        // if(!val){
                        //     return cb([]);
                        // }
                        var datas = {
                            pageIndex: pageIndex,
                            pageSize: 10,
                            keywords: val
                        };
                        utils.Ajax({
                            url: 'jobOrder/getPageList',
                            dataType: 'json',
                            type: 'post',
                            data: JSON.stringify(datas),
                            success: function(response) {
                                var res = response.data;
                                if(_.isArray(res.records) && res.records.length) {
                                    //回调需要两个参数, 第一个: 数据数组, 第二个: 总页码
                                    cb(res.records, Math.ceil(res.total/datas.pageSize));
                                } else {
                                    cb([], 0);
                                }
                            }
                        })
                    },
                    on: function (data) {
                        var arr = data.arr;
                        if (arr.length) {
                            var orderId = arr[0].id;
                            var clientId = arr[0].clientId;
                            var positionName = arr[0].positionName;

                            if(orderId !== that.form.orderId) {
                                that.form.orderId = orderId;
                                that.form.clientId = clientId;
                                that.form.positionName = positionName;

                                that.jobInvoiceVos = []
                            }
                            that.resultFlag = true;
                            that.getAllTalent(that.form.orderId);

                            that.paymentData=[];
                            that.getPaymentData();
                        } else{
                            that.form.orderId = '';
                            that.form.clientId = '';
                            that.form.positionName = '';

                            // that.jobInvoiceVos = [];
                        }
                        that.getAgreementData(); // 合同
                    }
                });

                if (that.form.orderId) {
                    xmSelectItem.setValue([
                        { positionName: that.form.positionName, id: that.form.orderId},
                    ])
                }

                return xmSelectItem;
            }, // 订单
            getSelectedTalent: function (config) {
                var that = this;
                utils.Ajax({
                    url: 'api/finance/2_selectTalent.json',
                    dataType: 'json',
                    type: 'post',
                    data: config,
                    success: function (response) {
                        var list = response.data.list;
                        if (Array.isArray(list)) {
                            that.jobInvoiceVos = list;
                        }
                    }
                });
            }, // 已选择人才列表
            getAllTalent: function(id){
                var that = this;
                var _url = '';
                var _type = '';

                if (that.form.billingType == 0) {
                    _url = 'jobOrder/findJobOrderRecruit/' + id;
                    _type = 'get';
                } else if (that.form.billingType == 1) {
                    _url = 'jobOrder/getTalentList/' + id;
                    _type = 'post';
                }

                utils.Ajax({
                    url: _url,
                    dataType: 'json',
                    type: _type,
                    data: {},
                    success: function (response) {
                        var list = response.data;
                        if (Array.isArray(list)) {

                            list.forEach(function (item, index) {
                                var obj = item;
                                obj.talentId = item.id;
                                obj.talentNameCn = item.namecn;
                                // delete obj.id;
                                delete obj.namecn;
                            });
                            that.allTalent = list;
                            if (!that.jobInvoiceVos.length) {
                                // // that.jobInvoiceVos = that.allTalent;
                                // // that.resultFlag = false;
                                // var jobInvoiceVos = [];
                                // that.allTalent.forEach(function (item, index) {
                                //     var obj = item;
                                //     obj.talentId = item.id;
                                //     delete obj.id;
                                //     jobInvoiceVos.push(obj);
                                // });
                                // that.jobInvoiceVos = jobInvoiceVos
                                that.jobInvoiceVos = [].concat(that.allTalent);
                            }
                            that.resultFlag = false;
                        }
                    }
                });
            }, // 项目或者订单下所有人才列表

            createTalentItem: function(selectedUser) {
                // return {
                //     id: utils.generateUUID(),
                //     talentId: selectedUser.talentId,
                //     name: selectedUser.name,
                //     guaranteePeriod: selectedUser.guaranteePeriod,
                //     isNew: true
                // }
                var obj = {};
                obj = selectedUser;
                // obj.id = utils.generateUUID();

                return obj;
            }, // 创建新的候选人
            addTalentItem: function(selectedUser) {
                var index = this.addAfterIndex;
                if (index < 0) {
                    index = this.jobInvoiceVos.length
                }
                var newItem = this.createTalentItem(selectedUser);


                this.jobInvoiceVos.splice(index + 1, 0, newItem);
            }, // 添加候选人
            handleAddBtnClick: function (item) {
                var that = this;
                that.addAfterIndex = _.findIndex(that.jobInvoiceVos, function (obj) {
                    return obj.id === item.id
                });
                laytpl($('#tplCanSelectTalent').html()).render(that.canSelectTalent, function(html){
                    layer.open({
                        title: '新增候选人',
                        type: 1,
                        shade: 0.2,
                        area: ['1000px', '90%'],
                        content: html,
                        btn: ['确认', '取消'],
                        btnAlign: 'c',
                        success: function(layero, index){
                            form.render();
                            var talentCb = [];
                            form.on('checkbox(talentCb)', function(data){
                                if (data.elem.checked) {
                                    talentCb.push(parseInt(data.value))
                                } else {
                                    var index = talentCb.indexOf(data.value);
                                    talentCb.splice(index, 1);
                                }
                            });

                            form.on('submit(formSub)', function(data){
                                var newSelectTalent = _.filter(that.canSelectTalent, function (obj) {
                                    return talentCb.indexOf(obj.talentId) > -1
                                });
                                newSelectTalent.forEach(function (item) {
                                    that.addTalentItem(item);
                                });
                                layer.close(index);
                                return false;
                            });
                        },
                        yes: function (index, layero) {
                            layero.find('[lay-filter="formSub"]').click();
                        }
                    });
                });
            },
            handleDelete: function (item) {
                var index = _.findIndex(this.jobInvoiceVos, function (obj) {
                    return obj.talentId === item.talentId
                });
                if(index > -1) {
                    this.jobInvoiceVos.splice(index, 1)
                }
            },

            getChargeTypeData: function (val) {
                var that = this;
                utils.Ajax({
                    url: 'baseItem/getList',
                    dataType: 'json',
                    type: 'post',
                    data: JSON.stringify({}),
                    success: function (response) {
                        var list = response.data;
                        if (_.isArray(list)) {
                            list.forEach(function (item) {
                                if(!item || !item.text) {
                                    item.text = item.text || ''
                                }
                            });
                            that.chargeType = list;
                        } else {
                            that.chargeType = []
                        }
                    }
                });
            }, // 科目
            getSupplierData: function (val) {
                var that = this;
                utils.Ajax({
                    url: 'baseVendor/getList',
                    dataType: 'json',
                    type: 'post',
                    data: JSON.stringify({}),
                    success: function (response) {
                        var list = response.data;
                        if (_.isArray(list)) {
                            list.forEach(function (item) {
                                if(!item || !item.vendorName) {
                                    item.vendorName = item.vendorName || ''
                                }
                            });
                            that.supplier = list;
                        } else {
                            that.supplier = []
                        }
                    }
                });
            }, // 供应商

            initAgreement: function () {
                var that = this;
                var $agreementSelect = that.$refs.agreementSelect;
                if (!$agreementSelect) {
                    return null
                }
                if (!this.agreementSelect) {
                    this.agreementSelect = xmSelect.render({
                        el: $agreementSelect,
                        radio: true,
                        clickClose: true,
                        model: {
                            icon: 'hidden'
                        },
                        prop: {
                            name: 'name',
                            value: 'id',
                        },
                        name: 'contractNumber',
                        theme: {
                            color: '#84d0e8',
                        },
                        filterable: true,
                        data: [],
                        on: function (data) {
                            var arr = data.arr;
                            if (arr.length) {
                                that.form.contractNumber = arr[0].id;
                            } else{
                                that.form.contractNumber = '';
                            }
                        }
                    });
                }
                return this.agreementSelect
            },
            getAgreementData: function (val) {
                var that = this;
                if (that.form.clientId) {
                    utils.Ajax({
                        url: 'clnContractFiling/getContractList',
                        dataType: 'json',
                        type: 'post',
                        data: JSON.stringify({clientId: that.form.clientId}),
                        success: function (response) {
                            var list = response.data;

                            var initValue = val === undefined ? [] : [val];

                            if (!Array.isArray(list)) list = [];

                            that.initAgreement().update({
                                data: list,
                                initValue: initValue,
                                disabled: false
                            });
                        }
                    });
                } else {
                    that.initAgreement().update({
                        data: [],
                        disabled: true
                    });
                }

            }, // 合同

            initPaymentTerms: function () {
                var that = this;
                var $paymentTerms = that.$refs.paymentTerms;
                if (!$paymentTerms) {
                    return null
                }
                var xmSelectItem = xmSelect.render({
                    el: $paymentTerms,
                    radio: true,
                    clickClose: true,
                    layVerify: 'required',
                    model: {
                        icon: 'hidden'
                    },
                    prop: {
                        name: 'text',
                        value: 'text',
                    },
                    name: 'paymentTerms',
                    theme: {
                        color: '#84d0e8',
                    },
                    filterable: true,
                    data: [],
                    on: function (data) {
                        var arr = data.arr;
                        if (arr.length) {
                            that.form.paymentTerms = arr[0].text;
                        } else{
                            that.form.paymentTerms = '';
                        }
                    }
                });
                return xmSelectItem;
            },
            getPaymentTerms: function (val) {
                var that = this;
                utils.Ajax({
                    url: 'baseDataDictionary/getList/payment_terms',
                    dataType: 'json',
                    type: 'get',
                    data: '',
                    success: function (response) {
                        var list = response.data;
                        if (Array.isArray(list)) {
                            var initValue = val === undefined ? [] : [val];
                            that.initPaymentTerms().update({
                                data: list,
                                initValue: initValue
                            });
                        }
                    }
                });
            }, // payment Terms

            getReceiptType: function () {
                var that = this;
                utils.Ajax({
                    url: 'baseDataDictionary/getList/receipt_type',
                    dataType: 'json',
                    type: 'get',
                    data: {},
                    success: function (response) {
                        var list = response.data;
                        if (_.isArray(list)) {
                            that.receiptType = list
                        } else {
                            that.receiptType = []
                        }
                    }
                });
            }, // 收款比列类别
            getInvoiceType: function () {
                var that = this;
                utils.Ajax({
                    url: 'baseDataDictionary/getList/invoice_billing_type',
                    dataType: 'json',
                    type: 'get',
                    data: {},
                    success: function (response) {
                        var list = response.data;

                        if (_.isArray(list)) {
                            that.invoiceType = list
                        } else {
                            that.invoiceType = []
                        }
                    }
                });
            },
            getReasonType: function () {
                var that = this;
                utils.Ajax({
                    url: 'baseDataDictionary/getList/distribution_type',
                    dataType: 'json',
                    type: 'get',
                    data: {},
                    success: function (response) {
                        var list = response.data;
                        if (_.isArray(list)) {
                            that.distributionType = list
                        } else {
                            that.distributionType = []
                        }
                    }
                });
            }, // 收款比列类别
            getPaymentData: function () {
                var that = this;
                utils.Ajax({
                    url: 'clnBilling/getList',
                    dataType: 'json',
                    type: 'post',
                    data: JSON.stringify({clientId: that.form.clientId}),
                    success: function (response) {
                        var list = response.data;
                        if (_.isArray(list)) {
                            that.paymentData = list
                        } else {
                            that.paymentData = []
                        }
                    }
                });
            }, // 客户选项

            handleSubmitBtnClick: function() {
                var that = this;
                var obj = {};

                utils.copyObject(obj, that.form); // 基础表单

                var $talentItem = that.$refs.talentItem;
                var talentInfo = [];
                $talentItem.forEach(function(item) {
                    talentInfo.push(item.getData())
                });

                obj.jobInvoiceVos = talentInfo;

                //console.log(obj)

                utils.Ajax({
                    url: 'jobInvoice/saveJobInvoiceAndChild',
                    dataType: 'json',
                    type: 'post',
                    data: JSON.stringify(obj),
                    success: function (response) {
                        layer.msg(response.message, function () {
                            layer.close(parentIndex);
                            parent.layui.table.reload('financeTable');
                        });
                    }
                })
            } //提交
        }
    });


});
